﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity; 
using Microsoft.Practices.Unity.Configuration;

namespace SRF.Common
{
    /// <summary>
    /// 获取对象的工具类
    /// 
    /// </summary>
    public static class ObjectHelper
    {
        static IUnityContainer container;
        static Object lockObject = new Object();

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <returns></returns>
        public static T GetObject<T>(string name = "")
        {
            Init();

            if (!container.IsRegistered<T>() && !typeof(T).IsInterface)
            {
                container.RegisterType<T>(new ContainerControlledLifetimeManager());
            }

            return container.Resolve<T>(name);
        }   

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <typeparam name="TInterface">interface</typeparam>
        /// <typeparam name="TInstance">default class</typeparam>
        /// <returns></returns>
        public static TInterface GetObject<TInterface, TInstance>()
            where TInstance : class, TInterface
        {
            Init();

            if (!container.IsRegistered<TInterface>())
            {
                return container.Resolve<TInstance>();
            }
            else
            {
                return container.Resolve<TInterface>();
            }
        }

        private static void Init()
        {
            if (container == null)
            {
                lock (lockObject)
                {
                    if (container == null)
                    {
                        container = new UnityContainer().LoadConfiguration();
                    }
                }
            }
        }
    }
}